package com.driving.code.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.driving.code.entity.Answer;
import com.driving.code.entity.MyPage;
import com.driving.code.entity.ParseData;
import com.driving.code.entity.Question;
import com.driving.code.service.QuestionService;
import com.driving.code.utils.UploadUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 驾校一点通，题库信息表 前端控制器
 * </p>
 *
 * @author 喜欢编程的代先生
 * @since 2021-06-14
 */
@RestController
@RequestMapping("question")
public class QuestionController {
    @Resource
    private QuestionService questionService;
    @Resource
    private UploadUtils uploadUtils;

    /**
     * 顺序练习，获取下一题
     * @param current
     * @return
     */
    @RequestMapping("getNextQuestionBySequence/{classify}/{current}/{flag}")
    public MyPage getNextQuestionBySequence(@PathVariable(value = "current") Integer current,@PathVariable(value = "classify") Integer classify,@PathVariable(value = "flag") String flag){
        IPage<Question> page = new Page(current,1);
        IPage<Question> questionIPage = null;
        if ("sequence".equals(flag)){
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify));
        }
        if("mistakable".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify).ge(Question::getQuestionError,10));
        }
        if("uniterming".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify).eq(Question::getQuestionType,1));
        }
        if("multipleChoice".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify).eq(Question::getQuestionType,3));
        }
        if("trueOrFalse".equals(flag)) {
            questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify).eq(Question::getQuestionType,2));
        }
        if (questionIPage == null){
            return null;
        }
        MyPage<Question> myPage = new MyPage<>(questionIPage.getTotal(), questionIPage.getCurrent(), questionIPage.getRecords());
        return myPage;
    }

    /**
     * 通过ID查询指定的问题
     * @return
     */
    @RequestMapping("getNextQuestionById/{index}")
    public Question getNextQuestionById(@PathVariable(value = "index") Integer index,HttpSession session){
        List<Integer> ids_random = (ArrayList<Integer>) session.getAttribute("ids_random");
        Integer id = ids_random.get(index);
        Question question = questionService.getById(id);
        return question;
    }

    /**
     * 获取全部的问题ID
     * @param classify
     * @return
     */
    @RequestMapping("getAllQuestionIdsBySequence/{classify}/{flag}")
    public List<Integer> getAllQuestionIdsBySequence(@PathVariable(value = "classify") Integer classify,@PathVariable(value = "flag") String flag){
        List<Question> list = null;
        if ("sequence".equals(flag)){
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify));
        }

        if ("mistakable".equals(flag)){
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify).ge(Question::getQuestionError,10));
        }

        if ("uniterming".equals(flag)){
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify).eq(Question::getQuestionType,1));
        }

        if ("multipleChoice".equals(flag)){
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify).eq(Question::getQuestionType,3));
        }

        if ("trueOrFalse".equals(flag)){
            list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify,classify).eq(Question::getQuestionType,2));
        }

        ArrayList<Integer> arrayList = new ArrayList<>();
        for (Question question : list) {
            arrayList.add(question.getQuestionId());
        }
        return arrayList;
    }

    /**
     * 获取全部的ID，并打乱，模拟随机查询。
     * @param classify
     * @return
     */
    @RequestMapping("getAllQuestionIdsByRandom/{classify}")
    public List<Integer> getAllQuestionIdsByRandom(@PathVariable(value = "classify") Integer classify, HttpSession session){
        List<Integer> ids = this.getAllQuestionIdsBySequence(classify,"sequence");
        Collections.shuffle(ids);
        session.setAttribute("ids_random",ids);
        return ids;
    }

    /**
     * 获得全部的问题
     * @param current
     * @param size
     * @param search
     * @return
     */
    @RequestMapping("getAllQuestion")
    public ParseData getAllQuestion(@RequestParam(value = "page",required = false,defaultValue = "1")Integer current,
                                    @RequestParam(value = "limit",required = false,defaultValue = "12")Integer size,
                                    @RequestParam(value = "search",required = false) String search,
                                    @RequestParam(value = "classify",required = false) Integer classify){
        IPage<Question> page = new Page(current,size);
        LambdaQueryWrapper<Question> queryWrapper = new QueryWrapper<Question>().lambda();
        if (search != null && search != ""){
            queryWrapper.like(Question::getQuestionTopic, search);
        }
        if (classify !=  null){
            queryWrapper.eq(Question::getQuestionClassify,classify);
        }
        IPage<Question> questionIPage = questionService.page(page, queryWrapper);
        ParseData<Question> parseData = new ParseData<>();
        parseData.setData(questionIPage.getRecords());
        parseData.setCode(0);
        parseData.setCount(questionIPage.getTotal());
        parseData.setMsg("请求成功");
        return parseData;
    }


    /**
     * 添加问题
     * @param question
     * @return
     */
    @RequestMapping("addQuestion")
    public String addQuestion(Question question){
        Answer answer = question.getAnswer();
        StringBuffer questionAnswer = new StringBuffer();
        if (answer.getQuestionAnswerA() != null && answer.getQuestionAnswerA() != ""){
            questionAnswer.append(answer.getQuestionAnswerA());
        }
        if (answer.getQuestionAnswerB() != null && answer.getQuestionAnswerB() != ""){
            questionAnswer.append(answer.getQuestionAnswerB());
        }
        if (answer.getQuestionAnswerC() != null && answer.getQuestionAnswerC() != ""){
            questionAnswer.append(answer.getQuestionAnswerC());
        }
        if (answer.getQuestionAnswerD() != null && answer.getQuestionAnswerD() != ""){
            questionAnswer.append(answer.getQuestionAnswerD());
        }
        if (answer.getQuestionAnswerE() != null && answer.getQuestionAnswerE() != ""){
            questionAnswer.append(answer.getQuestionAnswerE());
        }
        if (answer.getQuestionAnswerF() != null && answer.getQuestionAnswerF() != ""){
            questionAnswer.append(answer.getQuestionAnswerF());
        }
        if (answer.getQuestionAnswerG() != null && answer.getQuestionAnswerG() != ""){
            questionAnswer.append(answer.getQuestionAnswerG());
        }
        question.setQuestionAnswer(questionAnswer.toString());
        boolean save = questionService.save(question);
        if (save){
            return "1";
        }
        return "0";
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    @RequestMapping("uploadImage")
    public ParseData uploadImage(MultipartFile file){
        String location = uploadUtils.upload(file);
        ParseData parseData = new ParseData();
        parseData.setMsg(location);
        return parseData;
    }

    /**
     * 设置考试的试题
     * @param questionId
     * @param questionTest
     * @return
     */
    @RequestMapping("setQuestionTest")
    public String setQuestionTest(Integer questionId,Boolean questionTest){
        Question question = questionService.getById(questionId);
        question.setQuestionTest(questionTest);
        boolean b = questionService.updateById(question);
        if (b){
            return "1";
        }
        return "0";
    }


    /**
     * 获得考试的试题
     * @param current
     * @param classify
     * @return
     */
    @RequestMapping("getTestQuestion/{classify}/{current}")
    public MyPage getTestQuestion(@PathVariable(value = "current") Integer current,@PathVariable(value = "classify") Integer classify){
        IPage<Question> page = new Page<>(current, 1);
        IPage<Question> questionIPage = questionService.page(page, new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionTest, true));
        MyPage<Question> myPage = new MyPage<>(questionIPage.getTotal(), questionIPage.getCurrent(), questionIPage.getRecords());
        return myPage;
    }

    /**
     * 获得考试问题的全部ID
     * @param classify
     * @return
     */
    @RequestMapping("getTestQuestionIds/{classify}")
    public List<Integer> getTestQuestionIds(@PathVariable(value = "classify") Integer classify){
        List<Question> list = questionService.list(new QueryWrapper<Question>().lambda().eq(Question::getQuestionClassify, classify).eq(Question::getQuestionTest,true));
        ArrayList<Integer> arrayList = new ArrayList<>();
        for (Question question : list) {
            arrayList.add(question.getQuestionId());
        }
        return arrayList;
    }

    /**
     * 删除问题
     * @param questionId
     * @return
     */
    @RequestMapping("deleteQuestion")
    public String deleteQuestion(Integer questionId){
        boolean delete = questionService.removeById(questionId);
        if (delete){
            return "1";
        }
        return "0";
    }


    /**
     * 如果用户回答错误，当前问题的错误数量加一。
     * @param questionId
     */
    @RequestMapping("questionError")
    public String questionError(Integer questionId){
        Question question = questionService.getById(questionId);
        question.setQuestionError(question.getQuestionError()+1);
        boolean b = questionService.updateById(question);
        if(b){
            return "1";
        }
        return "0";
    }


    /**
     * 设置科目一的考试  限时时间
     * @param request
     * @param time_limit
     * @return
     */
    @RequestMapping("subjectOneTestTime")
    @ResponseBody
    public String subjectOneTestTime(HttpServletRequest request, Integer time_limit){
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("time_limit_one",time_limit);
        return "1";
    }

    /**
     * 设置科目四的考试  限时时间
     * @param request
     * @param time_limit
     * @return
     */
    @RequestMapping("subjectFourTestTime")
    @ResponseBody
    public String subjectFourTestTime(HttpServletRequest request,Integer time_limit){
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("time_limit_four",time_limit);
        return "1";
    }
}

